package com.jwater.core.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @description:
 * @author: jnner
 * @createDate: 2021/2/5
 * @version: 1.0
 */
public class JdkSerialize extends AbstractSerialize {
    /**
     * JDK序列化
     *
     * @param obj
     * @param <T>
     * @return
     * @throws SerializeException
     */
    @Override
    public <T> byte[] serialize(T obj) throws SerializeException {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(obj);
            oos.close();
            baos.close();
            return baos.toByteArray();
        } catch (Exception e) {
            throw new SerializeException("JdkSerialize error", e);
        }
    }

    /**
     * JDK反序列化
     *
     * @param data
     * @param clazz
     * @param <T>
     * @return
     * @throws SerializeException
     */
    @SuppressWarnings("unchecked")
    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) throws SerializeException {
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(data);
            ObjectInputStream ois = new ObjectInputStream(bais);
            Object obj = ois.readObject();
            ois.close();
            bais.close();
            return (T) obj;
        } catch (Exception e) {
            throw new SerializeException("JdkDeserialize error", e);
        }
    }

}
